import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont, QBrush, QColor, QKeySequence
from PyQt5.QtWidgets import QWidget, QListWidgetItem, QApplication, QShortcut
import resources.resource_rc
from windowUI.touchKeyUI import Ui_TouchKeyWidget
from serialPort import cm3_pb2


class TouchKeyWindow(Ui_TouchKeyWidget, QWidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setupUi(self)
        # 引入公共程序
        from utils.common import commonProgram
        # 引入配置文件
        self.myConfig = commonProgram.EnableConfigHandler()
        print('TouchKeyWindow get config Version', self.myConfig.version)
        # 引入可控串口信息窗口
        commonProgram.EnableSerialPort(RecvSerialData=self.RecvSerialData)

        # 快捷键
        self.screenStatus = 'Normal'
        screenShortcut = QShortcut(QKeySequence(Qt.Key_F11), self)
        screenShortcut.activated.connect(self.WindowSizeFun)
        self.setToolTip('全屏与退出全屏：\n               F11')

        # 初始化触摸按键测试项
        self.myConfig.passTouchKeyItems = set()
        self.item_list1 = set()
        try:
            expr = f"self.touchKeyItems = self.myConfig.touchKeyItems.tou{self.myConfig.screenResolution}"
            exec(expr)
        except Exception as e:
            expr = f"self.touchKeyItems = self.myConfig.touchKeyItems.touDefault"
            exec(expr)
        for item in self.touchKeyItems:
            widItem = QListWidgetItem()
            widItem.setText(item['name'])
            # 设置字体（字体，字号，颜色）
            # widItem.setFont(QFont('Times', 32, QFont.Black))
            # 另外一种方法设置颜色（该为红色）
            widItem.setForeground(QBrush(QColor(len(self.item_list1) * 10 + 30, 0, len(self.item_list1) * 30 + 90)))
            # 设置背景色
            # widItem.setBackground(QBrush(QColor(0, 0, len(self.item_list1)*20)))
            self.item_list1.add(item['name'])
            self.listLeft.addItem(widItem)
        self.WindowSizeFun()

    def getList1Item(self, keyName):
        list1Count = self.listLeft.count()
        if list1Count <= 0:
            self.myConfig.passTestItems.add('TouchKey')
        for i in range(list1Count):
            item = self.listLeft.item(i)
            if item.text() in keyName:
                # print('found item ', item.text())
                self.listLeft.removeItemWidget(self.listLeft.takeItem(i))
                return item
        return None

    def TouchedFun(self, keyName):
        gItem = self.getList1Item(keyName=keyName)
        if gItem != None:
            # print('add item', gItem)
            self.listRight.addItem(gItem)
        self.myConfig.passTouchKeyItems.add(keyName)

    def RecvSerialData(self, dictData: dict):
        # 用于接收Form2发过来的数据
        # dataStr = dictData.get("data", None)  # num2 就是子界面传递过来的数据
        if self.isVisible():
            self.DataHandleFun(dictData)
            if len(self.myConfig.passTouchKeyItems) >= len(self.touchKeyItems):
                self.myConfig.passTestItems.add('TouchKey')
        # # type: send-发往串口，statusbar-显示在statusbar(状态栏)，text,.., - 显示在 textBrowser, null-不需要显示
        # print('-'*30)

    def DataHandleFun(self, dataDict: dict):
        typeStr = dataDict.get('type', 'null').strip()
        if typeStr == 'rece_protobuf':
            display = dataDict.get('data', '')
            if display.msg_type == cm3_pb2.Input:
                # print('recv ', display.input.key)
                for item in self.touchKeyItems:
                    if item['index'] == display.input.key:
                        self.TouchedFun(item['name'])

    def WindowSizeFun(self):
        # print(toStatus)
        if self.screenStatus == 'Normal':
            self.showFullScreen()
            self.screenStatus = 'FullScreen'
        else:
            self.showNormal()
            self.screenStatus = 'Normal'


if __name__ == '__main__':
    # 适应高DPI设备
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    # 解决图片在不同分辨率显示模糊问题
    QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)
    QApplication.setAttribute(Qt.AA_Use96Dpi)
    app = QApplication(sys.argv)
    font = QFont("宋体")
    pointsize = font.pointSize()
    font.setPixelSize(int(pointsize * 90 / 72))
    app.setFont(font)
    touchKeyWin = TouchKeyWindow()
    touchKeyWin.show()
    touchKeyWin.TouchedFun('return')
    sys.exit(app.exec_())
